<?php

namespace App\Admin\Controllers;

use App\Models\JxtBanner;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;

class BannerController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '轮播图';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new JxtBanner());

        $grid->column('id', __('Id'));
        $grid->column('image', __('图片'))->display(function ($image) {
            $img = "<img width='100'
                    src='" . url($image) . "'/>";
            return $img;
        });
        $grid->column('status', __('状态'))->display(function ($value) {
            $class = $value == JxtBanner::STATUS_SHOW ? 'label-success' : 'label-danger';
            return "<span class='label " . $class . "'>" . JxtBanner::$status[$value] . "</span>";
        });
        $grid->column('sort', __('排序'))->sortable();
        $grid->column('created_at', __('创建时间'));

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(JxtBanner::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('image', __('图片'))->unescape()->as(function ($image) {
            return "<img src='" . url('/uploads/' . $image) . "'/>";
        });
        $show->field('status', __('状态'));
        $show->field('sort', __('排序'));
        $show->field('created_at', __('创建日期'));
        $show->field('updated_at', __('更新日期'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new JxtBanner());

        $form->image('image', __('图片'))->move('images/banners/' . date('Ymd'))->uniqueName()->required();
        $is_open = [
            'off' => ['value' => 0, 'text' => JxtBanner::$status[JxtBanner::STATUS_HIDE], 'color' => 'danger'],
            'on' => ['value' => 1, 'text' => JxtBanner::$status[JxtBanner::STATUS_SHOW], 'color' => 'success'],
        ];
        $form->switch('status', __('是否显示'))->states($is_open)->default(JxtBanner::STATUS_SHOW);
        $form->number('sort', __('排序'))->default(0)->min(0);
        $form->saved(function (Form $form) {
            $form->model()->image = '/uploads/' . $form->model()->image;
            $form->model()->save();
        });

        return $form;
    }
}
